/*
========================================================================
 Name        : SDictionaryContainerView.cpp
 Author      : Nguyen Duc Trung - Huynh Vu Vuong Khoa
 Copyright   : Nguyen Duc Trung - Huynh Vu Vuong Khoa
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <akncontext.h>
#include <akntitle.h>
#include <stringloader.h>
#include <barsread.h>
#include <SDictionary.rsg>
// ]]] end generated region [Generated System Includes]

#include <S32FILE.H> 
#include <aknnotewrappers.h>
#include "Word.h"
#include "utf.h"

// [[[ begin generated region: do not modify [Generated User Includes]

#include "SDictionary.hrh"
#include "SDictionaryContainerView.h"
#include "SDictionaryContainer.hrh"
#include "SDictionaryContainer.h"
// ]]] end generated region [Generated User Includes]

// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]

/**
 * First phase of Symbian two-phase construction. Should not contain any
 * code that could leave.
 */
CSDictionaryContainerView::CSDictionaryContainerView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	iSDictionaryContainer = NULL;
	_LIT(FileName, "C:\\Data\\AnhViet_small.bin");
	iDictionaryFilePath.Format(FileName);
	// ]]] end generated region [Generated Contents]
	
	}

/** 
 * The view's destructor removes the container from the control
 * stack and destroys it.
 */
CSDictionaryContainerView::~CSDictionaryContainerView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	delete iSDictionaryContainer;
	iSDictionaryContainer = NULL;
	// ]]] end generated region [Generated Contents]
	
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance then calls the second-phase constructor
 * without leaving the instance on the cleanup stack.
 * @return new instance of CSDictionaryContainerView
 */
CSDictionaryContainerView* CSDictionaryContainerView::NewL()
	{
	CSDictionaryContainerView* self = CSDictionaryContainerView::NewLC();
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance, pushes it on the cleanup stack,
 * then calls the second-phase constructor.
 * @return new instance of CSDictionaryContainerView
 */
CSDictionaryContainerView* CSDictionaryContainerView::NewLC()
	{
	CSDictionaryContainerView* self = new ( ELeave ) CSDictionaryContainerView();
	CleanupStack::PushL( self );
	self->ConstructL();
	return self;
	}


/**
 * Second-phase constructor for view.  
 * Initialize contents from resource.
 */ 
void CSDictionaryContainerView::ConstructL()
	{
	// [[[ begin generated region: do not modify [Generated Code]
	BaseConstructL( R_SDICTIONARY_CONTAINER_SDICTIONARY_CONTAINER_VIEW );
				
	// ]]] end generated region [Generated Code]
	
	// add your own initialization code here
	
	}

/**
 * @return The UID for this view
 */
TUid CSDictionaryContainerView::Id() const
	{
	return TUid::Uid( ESDictionaryContainerViewId );
	}

/**
 * Handle a command for this view (override)
 * @param aCommand command id to be handled
 */
void CSDictionaryContainerView::HandleCommandL( TInt aCommand )
	{
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{	// code to dispatch to the AknView's menu and CBA commands is generated here
		case ESDictionaryContainerViewTestReadFileMenuItem1Command:
			commandHandled = HandleTestReadFileMenuItem1SelectedL( aCommand );
			break;
		default:
			break;
		}
	
		
	if ( !commandHandled ) 
		{
	
		}
	// ]]] end generated region [Generated Code]
	
	}

/**
 *	Handles user actions during activation of the view, 
 *	such as initializing the content.
 */
void CSDictionaryContainerView::DoActivateL( 
		const TVwsViewId& /*aPrevViewId*/,
		TUid /*aCustomMessageId*/,
		const TDesC8& /*aCustomMessage*/ )
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	SetupStatusPaneL();
	
				
	if ( iSDictionaryContainer == NULL )
		{
		iSDictionaryContainer = CreateContainerL();
		iSDictionaryContainer->SetMopParent( this );
		AppUi()->AddToStackL( *this, iSDictionaryContainer );
		} 
	// ]]] end generated region [Generated Contents]
	
	}

/**
 */
void CSDictionaryContainerView::DoDeactivate()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	CleanupStatusPane();
	
	if ( iSDictionaryContainer != NULL )
		{
		AppUi()->RemoveFromViewStack( *this, iSDictionaryContainer );
		delete iSDictionaryContainer;
		iSDictionaryContainer = NULL;
		}
	// ]]] end generated region [Generated Contents]
	
	}

/** 
 * Handle status pane size change for this view (override)
 */
void CSDictionaryContainerView::HandleStatusPaneSizeChange()
	{
	CAknView::HandleStatusPaneSizeChange();
	
	// this may fail, but we're not able to propagate exceptions here
	TVwsViewId view;
	AppUi()->GetActiveViewId( view );
	if ( view.iViewUid == Id() )
		{
		TInt result;
		TRAP( result, SetupStatusPaneL() );
		}
	
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	}

// [[[ begin generated function: do not modify
void CSDictionaryContainerView::SetupStatusPaneL()
	{
	// reset the context pane
	TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
	CEikStatusPaneBase::TPaneCapabilities subPaneContext = 
		StatusPane()->PaneCapabilities( contextPaneUid );
	if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
		{
		CAknContextPane* context = static_cast< CAknContextPane* > ( 
			StatusPane()->ControlL( contextPaneUid ) );
		context->SetPictureToDefaultL();
		}
	
	// setup the title pane
	TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle );
	CEikStatusPaneBase::TPaneCapabilities subPaneTitle = 
		StatusPane()->PaneCapabilities( titlePaneUid );
	if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() )
		{
		CAknTitlePane* title = static_cast< CAknTitlePane* >( 
			StatusPane()->ControlL( titlePaneUid ) );
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_SDICTIONARY_CONTAINER_TITLE_RESOURCE );
		title->SetFromResourceL( reader );
		CleanupStack::PopAndDestroy(); // reader internal state
		}
				
	}

// ]]] end generated function

// [[[ begin generated function: do not modify
void CSDictionaryContainerView::CleanupStatusPane()
	{
	}

// ]]] end generated function

/**
 *	Creates the top-level container for the view.  You may modify this method's
 *	contents and the CSDictionaryContainer::NewL() signature as needed to initialize the
 *	container, but the signature for this method is fixed.
 *	@return new initialized instance of CSDictionaryContainer
 */
CSDictionaryContainer* CSDictionaryContainerView::CreateContainerL()
	{
	return CSDictionaryContainer::NewL( ClientRect(), NULL, this );
	}

void CSDictionaryContainerView::TestReadFile()
	{
		RFs fsSession;
		User::LeaveIfError(fsSession.Connect());
		RFile file;
		User::LeaveIfError(file.Open(fsSession, iDictionaryFilePath, EFileShareExclusive|EFileRead));
		RFileReadStream reader(file);
		reader.PushL();
		//read
		TInt iNumPrimaryIndex=reader.ReadInt32L();
		//HBufC8* bufTemp = HBufC8::NewL(len);
		//TPtr8 ptrTemp = bufTemp->Des();
		//reader.ReadL(ptrTemp, len);
		_LIT(KResult, "So luong chi muc cap 1: %d\n");
		TBuf<256> bufRes;
		bufRes.Format(KResult, iNumPrimaryIndex);
		CAknInformationNote *pNote;// = new (ELeave) CAknInformationNote();
		//pNote->ExecuteLD(bufRes);
		
		//TFixedArray<CPrimaryIndex*, iNumPrimaryIndex> iPrimaryIndexSystem; 
		CPrimaryIndex* iPrimaryIndexSystem = new (ELeave) CPrimaryIndex[iNumPrimaryIndex];
		CleanupStack::PushL(iPrimaryIndexSystem);
		reader.ReadL((TUint8*)iPrimaryIndexSystem, iNumPrimaryIndex*sizeof(CPrimaryIndex));
		for (int i = 0; i < iNumPrimaryIndex; ++i)
		{
			pNote = new (ELeave) CAknInformationNote();
			_LIT(KTemp, "Chu cai dau tien %c");
			bufRes.Format(KTemp, iPrimaryIndexSystem[i].iFirstChar);
			pNote->ExecuteLD(bufRes);
		}
		/*
		//1. Declare
		CArrayFixFlat<CPrimaryIndex>* iPrimaryIndexSystem;
		iPrimaryIndexSystem =new (ELeave) CArrayFixFlat<CPrimaryIndex>(5);
		CleanupStack::PushL(iPrimaryIndexSystem);
		//2. Use
		CPrimaryIndex temp_primaryIndex;
		
		//for (TInt i = 0; i < 5; i++)
			{
				reader.ReadL((TUint8*)&temp_primaryIndex, sizeof(CPrimaryIndex));
				iPrimaryIndexSystem->AppendL(temp_primaryIndex);
				TPtrC ptr(&(iPrimaryIndexSystem->operator [](0).iFirstChar));
				pNote->ExecuteLD(ptr);
			}
		
		*/
		//3. Delete
		CleanupStack::PopAndDestroy(iPrimaryIndexSystem);
		
		CleanupStack::PopAndDestroy(); //destroy reader
		//CleanupStack::PopAndDestroy(iPrimaryIndexSystem);
		file.Close();
		fsSession.Close();
	}


	CPrimaryIndex CSDictionaryContainerView::FindPrimaryIndex(TPtr aWord)
		{
				aWord.LowerCase();
				RFs fsSession;
				User::LeaveIfError(fsSession.Connect());
				RFile file;
				User::LeaveIfError(file.Open(fsSession, iDictionaryFilePath, EFileShareExclusive|EFileRead));
				RFileReadStream reader(file);
				reader.PushL();
				
				TInt iNumPrimaryIndex=reader.ReadInt32L();
				
				int index = -1;
				CPrimaryIndex* iPrimaryIndexSystem = new (ELeave) CPrimaryIndex[iNumPrimaryIndex];
				CleanupStack::PushL(iPrimaryIndexSystem);
				reader.ReadL((TUint8*)iPrimaryIndexSystem, iNumPrimaryIndex*sizeof(CPrimaryIndex));
				
				for (int i = 0; i < iNumPrimaryIndex; ++i)
				{
					if (aWord.operator [](0) == iPrimaryIndexSystem[i].iFirstChar)
						{
							index = i;
							break;
						}
				}
				CleanupStack::Pop(iPrimaryIndexSystem);
				CleanupStack::PopAndDestroy(); //destroy reader
				file.Close();
				fsSession.Close();
				if (index != -1)
					return iPrimaryIndexSystem[index];
				CPrimaryIndex null;
				return null;
		}
	CSecondaryIndex CSDictionaryContainerView::FindSecondaryIndex(CPrimaryIndex aPriIndex, TPtr aWord)
		{
			//aWord.LowerCase();
			RFs fsSession;
			User::LeaveIfError(fsSession.Connect());
			RFile file;
			User::LeaveIfError(file.Open(fsSession, iDictionaryFilePath, EFileShareExclusive|EFileRead));
			RFileReadStream reader(file, aPriIndex.iOffset);
			reader.PushL();
			
			TInt iNumSecIndex = aPriIndex.iLength/sizeof(CSecondaryIndex);
			CSecondaryIndex* iSecondaryIndexSystem = new (ELeave) CSecondaryIndex[iNumSecIndex];
			CleanupStack::PushL(iSecondaryIndexSystem);
			
			reader.ReadL((TUint8*)iSecondaryIndexSystem, aPriIndex.iLength);
			
			int index = -1;
			for (int i = 0; i < iNumSecIndex; ++i)
				{
					if ((aWord[0] == iSecondaryIndexSystem[i].iTwoFirstChar[0]) 
					    && aWord[1] == iSecondaryIndexSystem[i].iTwoFirstChar[1])
						{
							index = i;
							break;
						}
				}
			CleanupStack::Pop(iSecondaryIndexSystem);
			CleanupStack::PopAndDestroy(); //destroy reader
			file.Close();
			fsSession.Close();
			if (index != -1)
				return iSecondaryIndexSystem[index];
			CSecondaryIndex null;
			return null;
		}
	CKeyWord CSDictionaryContainerView::FindKeyword(CSecondaryIndex aSecIndex, TPtr aWord)
		{
			RFs fsSession;
			User::LeaveIfError(fsSession.Connect());
			RFile file;
			User::LeaveIfError(file.Open(fsSession, iDictionaryFilePath, EFileShareExclusive|EFileRead));
			RFileReadStream reader(file, aSecIndex.iOffset);
			reader.PushL();
			
			TInt iNumKeyword = aSecIndex.iLength/sizeof(CKeyWord);
			CKeyWord* iKeywordSystem = new (ELeave) CKeyWord[iNumKeyword];
			CleanupStack::PushL(iKeywordSystem);
		
			reader.ReadL((TUint8*)iKeywordSystem, aSecIndex.iLength);
			
			int index = -1;
			for (int i = 0; i < iNumKeyword; i++)
				{
					TInt len = aWord.Length();
					int j = 0;
					TBool iMatch = false;
					if (iKeywordSystem[i].iKeyword[len] == 0)	// same length
						while (j < len)
							{
								if (iKeywordSystem[i].iKeyword[j] != aWord[j])
									break;
								++j;
								if (j == len)
									iMatch = true;
							}
					if (iMatch)
						{
							index = i;
							break;
						}
				}
			
			CleanupStack::Pop(iKeywordSystem);
			CleanupStack::PopAndDestroy(); //destroy reader
			file.Close();
			fsSession.Close();
			if (index != -1)
				return iKeywordSystem[index];
			CKeyWord null;
			return null;
		
		}
	HBufC* CSDictionaryContainerView::FindMeaning(CKeyWord aKeyword)
		{
			RFs fsSession;
			User::LeaveIfError(fsSession.Connect());
			RFile file;
			User::LeaveIfError(file.Open(fsSession, iDictionaryFilePath, EFileShareExclusive|EFileRead));
			RFileReadStream reader(file, aKeyword.iMeaningOffset);
			reader.PushL();
			
			int iNumChar = aKeyword.iMeaningLength/sizeof(TText);
			TUint16* temp = new (ELeave)TUint16[iNumChar + 1];
			CleanupStack::PushL(temp);
			reader.ReadL((TUint8*)temp, aKeyword.iMeaningLength);
			temp[iNumChar] = 0;
			HBufC* result = HBufC::NewLC(iNumChar + 1);
			*result = temp;
			

			CleanupStack::Pop(result);
			CleanupStack::Pop(temp);
			CleanupStack::PopAndDestroy(); //destroy reader
			file.Close();
			fsSession.Close();
			return result;
		}
	HBufC* CSDictionaryContainerView::Find(TPtr aWord)
		{
			aWord.LowerCase();
			CPrimaryIndex iPriIndex = FindPrimaryIndex(aWord);
			if (iPriIndex.iOffset != -1)
				{
					CSecondaryIndex iSecIndex = FindSecondaryIndex(iPriIndex, aWord);
					if (iSecIndex.iOffset != -1)
						{
							CKeyWord iKeyword = FindKeyword(iSecIndex, aWord);
							if (iKeyword.iMeaningOffset != -1)
								{
									return FindMeaning(iKeyword);
								}
						}
				}
			
			_LIT(NotFound, "Khong tim thay tu nay");
			HBufC* result = HBufC::NewL(100);
			*result = NotFound;
			//CleanupStack::Pop(result);
			return result;
		}

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSDictionaryContainerView::HandleTestReadFileMenuItem1SelectedL( TInt aCommand )
	{
	// TODO: implement selected event handler
		CAknInformationNote *pNote = new (ELeave) CAknInformationNote();
		_LIT(w, "nucleon");
		TBufC<30> word(w);
		//TPtr word = w;
		HBufC* meaning = Find(word.Des()); 
		
		pNote->ExecuteLD(*meaning);
	
		return ETrue;
	}
				
